const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const dbConfig = {
    host: process.env.DB_HOST || "43.143.253.188",
    port: parseInt(process.env.DB_PORT || "3306", 10),
    user: process.env.DB_USER || "nextjs",
    password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
    database: process.env.DB_NAME || "nextjs",
    charset: 'utf8mb4',
    timezone: '+08:00',
    acquireTimeout: 60000,
    timeout: 60000,
};

// 读取装备基础数据JSON文件
function loadEquipmentData() {
    try {
        const jsonPath = path.join(__dirname, 'output', 'zb_0911.json');
        const jsonData = fs.readFileSync(jsonPath, 'utf8');
        return JSON.parse(jsonData);
    } catch (error) {
        console.error('❌ 读取装备基础数据JSON文件失败:', error.message);
        throw error;
    }
}

// 解析装备数据
function parseEquipmentData(equipmentData) {
    const equipment = {
        id: equipmentData.id,
        name: '',
        base: 0,
        level: 1,
        price: '0',
        type: 2, // 默认装备类型
        image: '',
        intro: '',
        weight: 0,
        req_level: 0,
        req_strength: 0,
        req_constitution: 0,
        req_agility: 0,
        req_intelligence: 0,
        bonus_attack: 0,
        bonus_hp: 0,
        bonus_mp: 0,
        bonus_defense: 0,
        resistance_type: null,
        resistance_value: 0
    };

    // 解析data数组中的键值对
    equipmentData.data.forEach(dataItem => {
        const key = dataItem.k;
        const value = dataItem.v;

        switch (key) {
            case '名称：':
                equipment.name = value;
                break;
            case '图片：':
                equipment.image = value;
                break;
            case '等级：':
                equipment.level = parseInt(value) || 1;
                break;
            case '负重：':
                equipment.weight = parseInt(value) || 0;
                break;
            case '效果：':
                // 解析效果，提取各种加成
                parseEffect(value, equipment);
                break;
            case '佩带条件：':
                // 解析佩戴条件
                parseRequirements(value, equipment);
                break;
            case '介绍：':
                equipment.intro = value;
                break;
        }
    });

    return equipment;
}

// 解析效果字符串
function parseEffect(effectStr, equipment) {
    if (!effectStr) return;

    // 攻击力加成
    const attackMatch = effectStr.match(/攻击力\+(\d+)/);
    if (attackMatch) {
        equipment.bonus_attack = parseInt(attackMatch[1]);
    }

    // 血量加成
    const hpMatch = effectStr.match(/血量\+(\d+)/);
    if (hpMatch) {
        equipment.bonus_hp = parseInt(hpMatch[1]);
    }

    // 魔法加成
    const mpMatch = effectStr.match(/魔法\+(\d+)/);
    if (mpMatch) {
        equipment.bonus_mp = parseInt(mpMatch[1]);
    }

    // 防御加成
    const defenseMatch = effectStr.match(/防御\+(\d+)/);
    if (defenseMatch) {
        equipment.bonus_defense = parseInt(defenseMatch[1]);
    }

    // 其他效果可以在这里添加
}

// 解析佩戴条件
function parseRequirements(reqStr, equipment) {
    if (!reqStr) return;

    // 等级需求
    const levelMatch = reqStr.match(/等级大于(\d+)/);
    if (levelMatch) {
        equipment.req_level = parseInt(levelMatch[1]);
    }

    // 力量需求
    const strengthMatch = reqStr.match(/力量大于(\d+)/);
    if (strengthMatch) {
        equipment.req_strength = parseInt(strengthMatch[1]);
    }

    // 体质需求
    const constitutionMatch = reqStr.match(/体质大于(\d+)/);
    if (constitutionMatch) {
        equipment.req_constitution = parseInt(constitutionMatch[1]);
    }

    // 敏捷需求
    const agilityMatch = reqStr.match(/敏捷大于(\d+)/);
    if (agilityMatch) {
        equipment.req_agility = parseInt(agilityMatch[1]);
    }

    // 智力需求
    const intelligenceMatch = reqStr.match(/智力大于(\d+)/);
    if (intelligenceMatch) {
        equipment.req_intelligence = parseInt(intelligenceMatch[1]);
    }
}

// 根据装备名称推断基础类型
function inferBaseType(name) {
    if (name.includes('锤') || name.includes('斧') || name.includes('刀') || name.includes('剑') || name.includes('枪') || name.includes('戟')) {
        return 1; // 武器
    } else if (name.includes('甲') || name.includes('铠') || name.includes('衣') || name.includes('袍')) {
        return 2; // 防具
    } else if (name.includes('盔') || name.includes('帽') || name.includes('冠')) {
        return 3; // 头盔
    } else if (name.includes('靴') || name.includes('鞋')) {
        return 4; // 鞋子
    } else if (name.includes('链') || name.includes('坠') || name.includes('环')) {
        return 5; // 项链
    } else if (name.includes('腕') || name.includes('镯') || name.includes('戒')) {
        return 6; // 护腕/戒指
    } else {
        return 2; // 默认防具
    }
}

async function importEquipmentBase() {
    let connection;

    try {
        console.log('🚀 开始导入装备基础数据...');

        // 连接数据库
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！');

        // 检查表是否存在
        const [tables] = await connection.execute("SHOW TABLES LIKE 'equipment_base'");
        if (tables.length === 0) {
            console.log('❌ equipment_base 表不存在，请先创建表结构');
            return;
        }

        console.log('✅ equipment_base 表存在');

        // 读取JSON数据
        console.log('📖 读取装备基础数据JSON文件...');
        const jsonData = loadEquipmentData();
        const equipmentIds = Object.keys(jsonData);
        console.log(`📊 找到 ${equipmentIds.length} 个装备数据`);

        // 清空现有数据
        console.log('🗑️ 清空现有装备基础数据...');
        await connection.execute('DELETE FROM equipment_base');
        console.log('✅ 现有数据已清空');

        // 导入新数据
        console.log('📥 开始导入装备基础数据...');

        const insertSql = `
      INSERT INTO equipment_base (
        id, name, base, level, price, type, image, intro, weight,
                 req_level, req_strength, req_constitution, req_agility, req_intelligence,
        bonus_attack, bonus_hp, bonus_mp, bonus_defense,
        resistance_type, resistance_value, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NULL)
    `;

        let successCount = 0;
        let errorCount = 0;

        for (const equipmentId of equipmentIds) {
            try {
                const equipmentData = jsonData[equipmentId];
                let equipment = parseEquipmentData(equipmentData);

                // 推断基础类型
                equipment.base = inferBaseType(equipment.name);

                const values = [
                    equipment.id,
                    equipment.name,
                    equipment.base,
                    equipment.level,
                    equipment.price,
                    equipment.type,
                    equipment.image,
                    equipment.intro,
                    equipment.weight,
                    equipment.req_level,
                    equipment.req_strength,
                    equipment.req_constitution,
                    equipment.req_agility,
                    equipment.req_intelligence,
                    equipment.bonus_attack,
                    equipment.bonus_hp,
                    equipment.bonus_mp,
                    equipment.bonus_defense,
                    equipment.resistance_type,
                    equipment.resistance_value
                ];

                await connection.execute(insertSql, values);
                console.log(`✅ 导入装备: ${equipment.name} (ID: ${equipment.id}) - 类型:${equipment.base}, 等级:${equipment.level}`);
                successCount++;

            } catch (error) {
                console.error(`❌ 导入装备失败: ID=${equipmentId}`, error.message);
                errorCount++;
            }
        }

        console.log('\n📊 导入结果统计:');
        console.log(`✅ 成功导入: ${successCount} 条记录`);
        console.log(`❌ 导入失败: ${errorCount} 条记录`);
        console.log(`📈 总计处理: ${equipmentIds.length} 条记录`);

        // 验证导入结果
        console.log('\n🔍 验证导入结果...');
        const [results] = await connection.execute('SELECT COUNT(*) as count FROM equipment_base');
        console.log(`📊 数据库中现有装备数量: ${results[0].count}`);

        // 统计装备类型分布
        const [typeStats] = await connection.execute(`
      SELECT base, COUNT(*) as count 
      FROM equipment_base 
      GROUP BY base 
      ORDER BY base
    `);

        console.log('\n📈 装备类型分布:');
        const typeNames = { 1: '武器', 2: '防具', 3: '头盔', 4: '鞋子', 5: '项链', 6: '护腕/戒指' };
        typeStats.forEach(stat => {
            const typeName = typeNames[stat.base] || `类型${stat.base}`;
            console.log(`  ${typeName}: ${stat.count} 个装备`);
        });

        // 统计等级分布
        const [levelStats] = await connection.execute(`
      SELECT level, COUNT(*) as count 
      FROM equipment_base 
      GROUP BY level 
      ORDER BY level
    `);

        console.log('\n📈 装备等级分布:');
        levelStats.forEach(stat => {
            console.log(`  等级 ${stat.level}: ${stat.count} 个装备`);
        });

        console.log('\n🎉 装备基础数据导入完成！');

    } catch (error) {
        console.error('❌ 导入过程中发生错误:', error);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 执行导入
if (require.main === module) {
    importEquipmentBase()
        .then(() => {
            console.log('✅ 脚本执行完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('❌ 脚本执行失败:', error);
            process.exit(1);
        });
}

module.exports = { importEquipmentBase, parseEquipmentData, inferBaseType };